﻿/* 
 * Shows how to use RfcSessionManager to ensure that multiple functions
 * can be used in the same user session.
 * 
 * RfcSessionManager is a simple implemenation of IRfcSessionProvider
 * that uses thread-Id as the session-Id
 * 
 * ZINCREMENT_COUNTER & ZGET_COUNTER were copied from
 * SAP function INCREMENT_COUNTER & GET_COUNER respectively
 */

using SAP.Middleware.Connector;
using static System.Console;

namespace NCoSession
{
    class SessionDemo
    {
        public void SessionContextDemo()
        {
            RfcDestination dest = DestinationProvider.GetSAPDestination();

            IRfcFunction fmIncCounter = dest.Repository.CreateFunction("ZINCREMENT_COUNTER");
            IRfcFunction fmGetCounter = dest.Repository.CreateFunction("ZGET_COUNTER");

            // BeginContext()与EndContext()配对，之间的函数调用处在同一个session
            RfcSessionManager.BeginContext(dest);
            int currentCounter = 0;

            try {
                // 调用 ZGET_COUNTER 5次
                for (int i = 0; i < 5; i++) {
                    fmIncCounter.Invoke(dest);
                }

                // 调用ZINCREMENT_COUNT 获取counter
                fmGetCounter.Invoke(dest);
                currentCounter = fmGetCounter.GetInt("GET_VALUE");

            }
            finally {
                // 结束Session上下文管理
                RfcSessionManager.EndContext(dest);
            }

            WriteLine(currentCounter);
        }
    }
}
